package com.xia.im.netty.quickstart;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * netty客户端模版
 */
@Slf4j
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        //线程组
        NioEventLoopGroup group = new NioEventLoopGroup();
        try{
            //客户端启动器
            Bootstrap bootstrap = new Bootstrap();
            //设置线程组
            bootstrap.group(group);
            //管道实现类型
            bootstrap.channel(NioSocketChannel.class);
            //各种处理器初始化的地方
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // 将自定义的处理器添加到管道中
                    ch.pipeline().addLast(new NettyClientHandler());
                }
            });
            System.out.println("客户端 ok..");
            //连接服务端，同步阻塞
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999).sync();
            //给关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }
}
